package bblgw

import (
	"encoding/json"
	"io/ioutil"
	"os"
	"path/filepath"
)

var gw_conf GatewayConfig

type GatewayConfig struct {
	UnixSock string `json:"gw.unixsock"`
	Listen   string `json:"gw.listen"`
	Cachedir string `json:"gw.cachedir"`

	Slaves     []string `json:"cluster.slaves"`
	Master     string   `json:"cluster.master"`
	Passphrase string   `json:"cluster.passphrase"`
	LogLevel   string   `json:"log.level"`
	LogFile    string   `json:"log.file"`
	_file      string
}

func init_config(config string) error {
	filePath, err := filepath.Abs(config)
	if err != nil {
		return err
	}
	conf, err := read_config(filePath)
	if err != nil {
		return err
	}
	conf._file = filePath
	gw_conf = conf
	return nil
}

func read_config(file string) (config GatewayConfig, e error) {
	b, e := ioutil.ReadFile(file)
	if e != nil {
		return config, e
	}
	e = json.Unmarshal(b, &config)
	return
}

func write_config(config GatewayConfig) error {
	b, e := json.Marshal(config)
	if e != nil {
		return e
	}
	e = ioutil.WriteFile(config._file, b, os.ModePerm)
	if e != nil {
		return e
	}
	gw_conf = config
	return nil
}
